import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { updateI18nLanguage } from '@/i18n'

export const useLanguageStore = defineStore('language', {
  state: () => ({
    currentLanguage: getInitialLanguage()
  }),
  actions: {
    setLanguage (lang) {
      if (['zh', 'en'].includes(lang)) {
        this.currentLanguage = lang
        Cookies.set('language', lang, { expires: 365 }) // 设置cookie, 一年有效

        // 切换 vue-i18n 语言
        updateI18nLanguage(lang)
      }
    }
  }
})

function getInitialLanguage () {
  const cookieLang = Cookies.get('language')
  if (cookieLang) {
    return cookieLang
  }
  const browserLang = navigator.language
  return browserLang.startsWith('zh') ? 'zh' : 'en'
}
